package warm100;

import utils.ListNode;

import java.util.Stack;

public class isPalindrome_234 {
    public boolean isPalindrome(ListNode head) {
        //用栈速度比较慢
        if (head.next == null || head == null)
            return true;
        Stack<Integer> s = new Stack<>();
        ListNode slow = head;
        ListNode fast = head;
        while(fast != null && fast.next != null) {
            s.push(slow.val);
            slow = slow.next;
            fast = fast.next.next;
        }
        if (fast != null)             //奇数个跳过中间数
            slow = slow.next;
        while (slow != null) {
            if (s.pop() != slow.val)
                return false;
            slow = slow.next;
        }
        return true;
    }

    //快慢指针找到中点前半段反转链表
    public boolean isPalindrome2(ListNode head) {
        if(head == null || head.next == null) {
            return true;
        }
        ListNode slow = head, fast = head;
        ListNode pre = head, prepre = null;   //prepre为工作指针，pre永远为最前面节点
        while(fast != null && fast.next != null) {
            pre = slow;
            slow = slow.next;
            fast = fast.next.next;
            pre.next = prepre;
            prepre = pre;
        }
        if(fast != null) {
            slow = slow.next;
        }
        while(pre != null && slow != null) {
            if(pre.val != slow.val) {
                return false;
            }
            pre = pre.next;
            slow = slow.next;
        }
        return true;
    }

}
